package com.nus.listener;

import oracle.jdbc.pool.OracleDataSource;
import oracle.jdbc.xa.client.OracleXADataSource;
import org.apache.log4j.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/15/12
 * Time: 10:19 PM
 * To change this template use File | Settings | File Templates.
 */
public class DataSourceInitListener implements ServletContextListener {
    private Logger logger = Logger.getLogger(this.getClass());

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();

        try {
            OracleDataSource dataSource = new OracleXADataSource();
            String dbUserName = servletContext.getInitParameter("db_user_name");
            String dbPassword = servletContext.getInitParameter("db_password");
            String dbUrl = servletContext.getInitParameter("db_url");
            String dbConnectionName = servletContext.getInitParameter("db_connection_name");

            dataSource.setUser(dbUserName);
            dataSource.setPassword(dbPassword);
            dataSource.setURL(dbUrl);

            Connection databaseConnection = dataSource.getConnection();

            servletContext.setAttribute(dbConnectionName, databaseConnection);

        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        } finally {

        }
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        String dbConnectionName = servletContext.getInitParameter("db_connection_name");
        Connection databaseConnection = (Connection) servletContext.getAttribute(dbConnectionName);
        try {
            databaseConnection.close();
        } catch (SQLException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
